<?php

namespace app\common\controller;

/**
 * 微信授权相关接口
 *
 * @link http://www.phpddt.com
 */
class Payment extends Common
{
    function wx_pay($orderid, $money, $name, $openId)
    {
        $appid = 'wx0c7baa249e41dd4d';
        $mc_id = '1243139902';            //商户平台商户id必填 1481013912
        $backUrl = 'https://sh1149.cmsc888.com/iindex/Shop/notify';
        $key = '0909bc7bef4a1149626b2cc742f90f58';

        $postarray = array(
            "appid" => $appid,
            "body" => $name,
            "mch_id" => $mc_id,
            "openid" => $openId,
            "nonce_str" => md5(time()),
            "notify_url" => $backUrl,  //自已的网址  修改
            "out_trade_no" => $orderid,
            "spbill_create_ip" => get_client_ip(),
            "total_fee" => $money * 100,
            //"total_fee" => 1,
            "trade_type" => "JSAPI"
        );

        $postarray['sign'] = $this->mkSign($postarray, $key);

        $postdata = '<xml>';
        foreach ($postarray as $p => $v) {
            $postdata .= '<' . $p . '>' . $v . '</' . $p . '>';
        }
        $postdata .= '</xml>';

        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $data = $this->sendData($url, $postdata);
        $prepay_id = $this->getPrepayId($data);


        $data = array(
            "appid" => $appid,
            "noncestr" => md5(time()),
            "package" => "Sign=WXPay",
            "partnerid" => $mc_id,
            "prepayid" => $prepay_id,
            "timestamp" => time()
        );
        $data['sign'] = $this->mkSign($data, $key);
        return $data;
    }

    /**
     * 生成签名
     * @param $postarray
     * @param $appKey
     * @return string
     */
    function mkSign($postarray, $appKey)
    {
        ksort($postarray);
        $poststr = '';
        foreach ($postarray as $p => $v) {
            $poststr .= '&' . $p . '=' . $v;
        }
        $poststr .= '&key=' . $appKey;
        return strtoupper(md5(substr($poststr, 1)));
    }

    function getPrepayId($data)
    {
        $ob = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        $res = json_decode(json_encode($ob), true);
        return $res['prepay_id'];
    }

    function sendData($url, $data)
    {
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }
}
